package com.itic.web.pay.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.ht.mem.order.persistence.model.MemberOrder;
import com.itic.web.pay.config.XmlUtil1;
import com.itic.web.pay.service.WeiXinService;
import com.itic.web.qo.TokenData;

@Controller
@RequestMapping(value="/app/weixinPay")
public class WeixinPay {


   @Resource
    private WeiXinService weiXinService;
	/**
	 * 微信支付
	 * @param info
	 * @return
	 */
	@RequestMapping(value="/signwx",method={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Map<String,Object> signwx(HttpServletRequest request) {
		TokenData data=new TokenData ();
		data.setToken(request.getParameter("token"));
		MemberOrder temp =new MemberOrder();
		String itemId=request.getParameter("itemId");
		String orderType =request.getParameter("orderType");
		temp.setOrderType(orderType);
		return  weiXinService.precreateOrderByWX(temp,data,itemId,request);
	}
	
	
	
	/**
	 * 微信回調
	 * @param info
	 * @return
	 */
	@RequestMapping(value = "/successWx")
	@ResponseBody
	public Map<String,String> successWx(HttpServletRequest request,HttpServletResponse response) {
		  System.out.println("jinru   weixin zhifu huidiao");
		Map<String,String> map =new HashMap<String,String>();
		map.put("return_code", "SUCCESS");
		map.put("return_msg", "OK");
		  InputStream in=null;
	    try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");  
		    response.setContentType("text/html;charset=UTF-8");  
		    response.setHeader("Access-Control-Allow-Origin", "*"); 
		     in=request.getInputStream();  
		     ByteArrayOutputStream out=new ByteArrayOutputStream();  
			    byte[] buffer =new byte[1024];  
			    int len=0;  
			    while((len=in.read(buffer))!=-1){  
			        out.write(buffer, 0, len);  
			    }  
			    out.close();  
			    in.close();  
			    String msgxml=new String(out.toByteArray(),"utf-8");//xml数据  
			    System.out.println("wechat  huidiao &************"+msgxml); 
			    Map<Object, Object> bean = XmlUtil1.xmlToBean(msgxml);
			   
			    if(bean.get("return_code").equals("SUCCESS")&&bean.get("out_trade_no")!=null&&bean.get("transaction_id")!=null){
			    	weiXinService.completeOrder(bean);
			    }

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}  
	   
		return map;

	}
	
	
	
}